package framework;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * Created by Administrator on 2017/9/28.
 */
public class MappingClient {

    @Autowired
    private IndexClient indexClient;

    MappingClient(){};
    /**
     * 表与表之间的字段名相同，但是类型不同会报错，要注意保持一致
     * 如果后期需要动态加字段，只需要重新执行该方法就可以了，相当于修改了数据结构
     * @param indexName
     * @param type
     * @param mappingJson
     * @throws Exception
     */
    public  boolean createOrUpdateMapping(String indexName,String type,String mappingJson) throws Exception {
        PutMappingRequest mappingRequest = Requests.putMappingRequest(indexName).type(type).source(mappingJson, XContentType.JSON);
        PutMappingResponse response = indexClient.getClient().admin().indices().putMapping(mappingRequest).actionGet();
        return  response.isAcknowledged();
    }

    /**
     * 不同表名的字段名如果相同，filed必须一样
     * @param type
     */
    public static String demo(String type){
        try {
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject(type)
                    .startObject("properties")
                    .startObject("propertyId").field("type","long").endObject()
                    .startObject("name").field("type","keyword").field("store", "yes").field("index", "not_analyzed").endObject()
                    .startObject("time").field("type","long").endObject()
                    .startObject("buildingName").field("type", "keyword").field("store", "yes").field("index", "not_analyzed").field("null_value", "").endObject()
                    .endObject()
                    .endObject()
                    .endObject();

            return  builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
